<?php
// 文件签名
use JetBrains\PhpStorm\NoReturn;

$fileValue = '';
// 最低php版本要求
define('PHP_EDITION', '8.0');
// 服务环境检测
if (function_exists('saeAutoLoader') || isset($_SERVER['HTTP_BAE_ENV_APPID'])) {
    showHtml('对不起，当前环境不支持本系统，请使用独立服务或云主机！');
}

define('APP_DIR', _dir_path(substr(dirname(__FILE__), 0, -15))); // 项目目录
define('SITE_DIR', _dir_path(substr(dirname(__FILE__), 0, -8))); // 入口文件目录

if (file_exists('kginstall.lock')) {
    showHtml('你已经安装过该系统，如果想重新安装，请先删除public目录下的 kginstall.lock 文件，然后再安装。');
}

@set_time_limit(1000);

if ('8.0' > phpversion()) {
    exit('您的php版本过低，不能安装本软件，兼容php版本8.0+，谢谢！');
}

date_default_timezone_set('PRC');
error_reporting(E_ALL & ~E_NOTICE);
header('Content-Type: text/html; charset=UTF-8');

// 数据库
$sqlFile = 'kitegoadmin.sql';
$configFile = '.env';
if (!file_exists(SITE_DIR . 'install/' . $sqlFile) || !file_exists(SITE_DIR . 'install/' . $configFile)) {
    echo '缺少必要的安装文件!';
    exit;
}

// 安装版本信息
$versionInfo = getVersion();

// 当前步骤
$step = $_GET['step'] ?? ($_POST['step'] ?? 0);

// 地址
$scriptName = !empty($_SERVER["REQUEST_URI"]) ? $scriptName = $_SERVER["REQUEST_URI"] : $scriptName = $_SERVER["PHP_SELF"];
$rootPath = @preg_replace("/\/(I|i)nstall\/index\.php(.*)$/", "", $scriptName);
$domain = empty($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : $_SERVER['SERVER_NAME'];
if ($_SERVER['SERVER_PORT'] != 80) {
    $domain .= ":" . $_SERVER['SERVER_PORT'];
}
$domain = $domain . $rootPath;

// 是否满足
$yes = '<i class="layui-icon layui-icon-ok-circle" style="color:#67C23A"></i>';
$no = '<i class="layui-icon layui-icon-close-fill" style="color:#F56C6C"></i>';

// 模版报错信息
$hasError = false;
$errorMessage = '';

switch ($step) {
    case '0':
        include_once("templates/step0.php");
        exit();
    case '1':
        $phpv = phpversion();
        if ($phpv < '8.0') {
            die('本系统需要PHP为 8.0+ 版本，当前PHP版本为：' . phpversion());
        }

        $mysql = function_exists('mysqli_connect') ? $yes : $no;

        $fileinfo = extension_loaded('fileinfo') ? $yes : $no;

        $exif = extension_loaded('exif') ? $yes : $no;

        $tmp = function_exists('gd_info') ? gd_info() : [];
        $gd = !empty($tmp['GD Version']) ? $yes : $no;

        $curl = function_exists('curl_init') ? $yes : $no;

        $openssl = function_exists('openssl_encrypt') ? $yes : $no;

        $passOne = 0;
        if ($mysql == $yes &&  $fileinfo == $yes && $exif== $yes &&  $gd == $yes && $curl == $yes && $openssl == $yes) {
            $passOne = 1;
        }

        include_once("./templates/step1.php");
        exit();
    case '2':
        $passTwo = 1;
        $folder = ['.version', 'public', 'public/kgbackend', 'runtime'];
        $folderLimits = [];
        foreach ($folder as $dir) {
            if (!is_file(APP_DIR . $dir)) {
                if (!is_dir(APP_DIR . $dir)) {
                    dir_create(APP_DIR . $dir);
                }
            }

            $folderLimits[$dir][0] = !test_write(APP_DIR . $dir) ? $no : $yes;
            $folderLimits[$dir][1] = !is_readable(APP_DIR . $dir) ? $no : $yes;

            if ($folderLimits[$dir][0] == $no || $folderLimits[$dir][1] == $no) {
                $passTwo = 0;
            }
        }

        include_once("./templates/step2.php");
        exit();
    case '3':
        if (
            empty($_POST['dbHost']) ||
            empty($_POST['dbPort']) ||
            empty($_POST['dbName']) ||
            empty($_POST['dbPrefix']) ||
            empty($_POST['dbUser']) ||
            empty($_POST['dbPwd']) ||
            empty($_POST['adminName']) ||
            empty($_POST['adminPwd']) ||
            empty($_POST['adminPwd2'])
        ) {
            include_once("./templates/step3.php");
            exit();
        }

        if ($_POST['adminPwd'] != $_POST['adminPwd2']) {
            $hasError = true;
            $errorMessage = "二次密码不一致";
            include_once("./templates/step3.php");
            exit();
        }

        try {
            $dbName = strtolower(trim($_POST['dbName']));
            $conn = mysqli_init();
            mysqli_options($conn, MYSQLI_OPT_CONNECT_TIMEOUT, 2);
            @mysqli_real_connect($conn, $_POST['dbHost'], $_POST['dbUser'], $_POST['dbPwd'], NULL, $_POST['dbPort']);
            if (mysqli_get_server_info($conn) < 5.1) {
                throw new Exception('mysql版本过低');
            }
            $result = mysqli_query($conn, "SELECT @@global.sql_mode");
            $result = $result->fetch_array();
            $mysqlVersion = mysqli_get_server_info($conn);
            if ($mysqlVersion >= 5.7) {
                if (strstr($result[0], 'STRICT_TRANS_TABLES') || strstr($result[0], 'STRICT_ALL_TABLES') || strstr($result[0], 'TRADITIONAL') || strstr($result[0], 'ANSI'))
                    throw new Exception('数据库配置需要修改');
            }
            $result = mysqli_query($conn, "select count(table_name) as c from information_schema.`TABLES` where table_schema='$dbName'");
            $result = $result->fetch_array();
            if ($result['c'] > 0) {
                mysqli_close($conn);
                throw new Exception('数据库已存在');
            } else {
                mysqli_select_db($conn, $dbName);
                mysqli_close($conn);
                exit(json_encode(['code' => 200])); // 数据库配置成功
            }
        } catch (Exception $e) {
            if ($e->getCode() == 2002) {
                $message = '地址或端口错误';
            } else if ($e->getCode() == 1045) {
                $message = '用户名或密码错误';
            } else if ($e->getCode() == 1049) {
                try {
                    // 创建数据时同时设置编码
                    mysqli_query($conn, "CREATE DATABASE IF NOT EXISTS `" . $dbName . "` DEFAULT CHARACTER SET utf8mb4;");
                    mysqli_select_db($conn, $dbName);
                    mysqli_close($conn);
                    exit(json_encode(['code' => 200])); // 数据库配置成功
                } catch (Exception $e) {
                    exit(json_encode(['code' => 400, 'message' => $e->getCode() . '|' . $message . '|' . $e->getLine()]));
                }
            } else {
                $message = $e->getMessage();
            }
            exit(json_encode(['code' => 400, 'message' => $e->getCode() . '|' . $message . '|' . $e->getLine()]));
        }
    case '4':
        if (empty($_POST)) {
            header('Location: ' . '/install/index.php?step=3');
            exit;
        }
        if (isset($_POST['install']) && $_POST['install'] == 0) {
            include_once("./templates/step4.php");
            exit();
        }

        if (!isset($_POST['n'])) {
            header($domain . '/install/index.php?step=3');
        }

        // 已安装
        if ($_POST['n'] == 999999) {
            exit;
        }

        try {
            $conn = @mysqli_connect($_POST['dbHost'], $_POST['dbUser'], $_POST['dbPwd'], NULL, $_POST['dbPort']);
            if (mysqli_connect_errno()) {
                exit(json_encode(['code' => 400, 'message' => "连接数据库失败!" . mysqli_connect_error()]));
            }
            mysqli_set_charset($conn, "utf8mb4");
            $mysqlVersion = mysqli_get_server_info($conn);
            if ($mysqlVersion < 5.7) {
                exit(json_encode(['code' => 400, 'message' => "数据库版本太低! 必须5.7以上!"]));
            }

            mysqli_select_db($conn, $_POST['dbName']);

            // 读取数据文件
            $sqlData = file_get_contents(SITE_DIR . 'install/' . $sqlFile);
            $sqlFormat = sql_split($sqlData, $_POST['dbPrefix']);

            // 执行SQL语句
            $counts = count($sqlFormat);
            if (isset($_SERVER['REQUEST_SCHEME'])) {
                $request_scheme = $_SERVER['REQUEST_SCHEME'];
            } else {
                if ($_SERVER['HTTPS'] == 'on') {
                    $request_scheme = 'https';
                } else {
                    $request_scheme = 'http';
                }
            }
            for ($i = $_POST['n']; $i < $counts; $i++) {
                $sql = trim($sqlFormat[$i]);
                if (strstr($sql, 'CREATE TABLE')) {
                    preg_match('/CREATE TABLE\s+(IF NOT EXISTS\s+)?`([^`]+)`\s*\(/', $sql, $matches);
                    mysqli_query($conn, "DROP TABLE IF EXISTS `$matches[2]`");
                    $sql = str_replace('`kg_', '`' . $_POST['dbPrefix'], $sql); // 替换表前缀
                    $ret = mysqli_query($conn, $sql);
                    if ($ret) {
                        $message = '创建数据表[' . $_POST['dbPrefix'] . $matches[2] . ']完成!';
                    } else {
                        $err = mysqli_error($conn);
                        $message = '创建数据表[' . $_POST['dbPrefix'] . $matches[2] . ']失败!失败原因：' . $err;
                    }
                    $i++;
                    exit(json_encode(['code' => 200, 'n' => $i, 'count' => $counts, 'msg' => $message, 'time' => date('Y-m-d H:i:s')]));
                } else {
                    if (trim($sql) == '') {
                        continue;
                    }
                    $sql = str_replace('`kg_', '`' . $_POST['dbPrefix'], $sql); // 替换表前缀
                    $sql = str_replace('http://kitegoadmin.local', $request_scheme . '://' . $_SERVER['SERVER_NAME'], $sql); // 替换图片域名
                    $sql = str_replace('http:\\\\/\\\\/kitegoadmin.local', $request_scheme . ':\\\\/\\\\/' . $_SERVER['SERVER_NAME'], $sql); // 替换图片域名
                    $ret = mysqli_query($conn, $sql);
                    $message = '';
                    $arr = ['code' => 200, 'n' => $i, 'count' => $counts, 'msg' => $message, 'time' => date('Y-m-d H:i:s')];
                }
            }

            // 替换env数据库配置
            $strConfig = file_get_contents(SITE_DIR . 'install/' . $configFile);
            $strConfig = str_replace('#DOMAIN#', $domain, $strConfig);
            $strConfig = str_replace('#DB_HOST#', $_POST['dbHost'], $strConfig);
            $strConfig = str_replace('#DB_NAME#', $_POST['dbName'], $strConfig);
            $strConfig = str_replace('#DB_USER#', $_POST['dbUser'], $strConfig);
            $strConfig = str_replace('#DB_PASS#', $_POST['dbPwd'], $strConfig);
            $strConfig = str_replace('#DB_PORT#', $_POST['dbPort'], $strConfig);
            $strConfig = str_replace('#DB_PREFIX#', $_POST['dbPrefix'], $strConfig);
            $strConfig = str_replace('#DB_CHARSET#', 'utf8', $strConfig);
            @chmod(APP_DIR . '/.env', 0777); // 数据库配置文件的地址
            @file_put_contents(APP_DIR . '/.env', $strConfig); // 数据库配置文件的地址

            // 插入管理员表字段kg_admin表
            $time = time();
            $date = date('Y-m-d H:i:s', time());
            $ip = get_client_ip();
            $ip = empty($ip) ? "0.0.0.0" : $ip;
            $adminName = trim($_POST['adminName']);
            $adminPwd = password_hash($_POST['adminPwd'], PASSWORD_BCRYPT);
            mysqli_query($conn, "truncate table {$_POST['dbPrefix']}system_admin");
            $addAdminSql = "INSERT INTO `{$_POST['dbPrefix']}system_admin` (`id`, `uuid`, `account`, `password`, `nickname`, `avatar`, `real_name`, `phone`, `email`, `role_id`, `dept`, `login_count`, `login_failures`, `status`, `sort`, `delete_flag`, `create_time`, `update_time`, `delete_time`) VALUES
(1, '639006667278648977', '" . $adminName . "', '" . $adminPwd . "', 'kitego', '/static/img/admin/admin_avatar.png', '真实姓名', '15986366938', '123456789@qq.com', '1,2', 1, 1, 1, '1', 1120, 0, '" . $date . "', '" . $date . "', NULL)";
            $res = mysqli_query($conn, $addAdminSql);

            // 写入安装日志
            install_log();
            @touch('kginstall.lock');
            generateSignature();

            // 更改前端api
            $http = $_SERVER['REQUEST_SCHEME'];
            $configJs =<<<EOL
window.__APP_CONFIG__ = {
	APP_NAME: "KITEGO-Admin",
	API_URL: "{$http}://{$domain}/adminapi"
}
EOL;
            file_put_contents(APP_DIR . 'public/kgbackend/config.js', $configJs);

            exit(json_encode(['code' => 200, 'n' => 999999, 'count' => $counts, 'msg' => '安装完成', 'time' => date('Y-m-d H:i:s')]));
        } catch (Exception $e) {
            exit(json_encode(['code' => 400, 'message' => $e->getCode() . '|' . $e->getMessage() . '|' . $e->getLine()]));
        }
}

/**
 * 读取版本号
 */
function getVersion(): array
{
    $version = [];
    $file = @file(APP_DIR . '.version');
    foreach ($file as $line) {
        list($k, $v) = explode('=', $line);
        $version[$k] = $v;
    }

    return $version;
}

/**
 * 写入安装信息
 */
function install_log(): void
{
    $mt_rand_str = sp_random_string(8);
    $str_constant = "<?php" . PHP_EOL . "define('INSTALL_DATE'," . time() . ");" . PHP_EOL . "define('SERIAL_NUMBER','" . $mt_rand_str . "');";
    @file_put_contents('.constant', $str_constant);
}

/**
 * 文件是否可写
 * @param $d
 * @return bool
 */
function test_write($d): bool
{
    if (is_file($d)) {
        if (is_writeable($d)) {
            return true;
        }

    } else {
        $testFile = "_test.txt";
        $fp = @fopen($d . "/" . $testFile, "w");
        if (!$fp) {
            return false;
        }
        fclose($fp);
        $rs = @unlink($d . "/" . $testFile);
        if ($rs) {
            return true;
        }
    }

    return false;
}

/**
 * 处理sql文件
 * @param $sql
 * @param $dbPrefix
 * @return array
 */
function sql_split($sql, $dbPrefix): array
{
    if ($dbPrefix != "kg_") {
        $sql = str_replace("kg_", $dbPrefix, $sql);
    }

    $sql = preg_replace("/TYPE=(InnoDB|MyISAM|MEMORY)( DEFAULT CHARSET=[^; ]+)?/", "ENGINE=\\1 DEFAULT CHARSET=utf8", $sql);

    $sql = str_replace("\r", "\n", $sql);
    $ret = [];
    $num = 0;
    $queryArr = explode(";\n", trim($sql));
    unset($sql);
    foreach ($queryArr as $query) {
        $ret[$num] = '';
        $queryExp = explode("\n", trim($query));
        $queryExp = array_filter($queryExp);
        foreach ($queryExp as $vq) {
            $str1 = substr($vq, 0, 1);
            if ($str1 != '#' && $str1 != '-') {
                $ret[$num] .= $vq;
            }
        }
        $num++;
    }

    return $ret;
}

function _dir_path($path): array|string
{
    $path = str_replace('\\', '/', $path);
    if (!str_ends_with($path, '/'))
        $path = $path . '/';
    return $path;
}

/**
 * 获取客户端IP地址
 */
function get_client_ip()
{
    static $ip = NULL;
    if ($ip !== NULL)
        return $ip;
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        $pos = array_search('unknown', $arr);
        if (false !== $pos)
            unset($arr[$pos]);
        $ip = trim($arr[0]);
    } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $ip = (false !== ip2long($ip)) ? $ip : '0.0.0.0';

    return $ip;
}

function dir_create($path): bool
{
    if (is_dir($path)) {
        return true;
    }
    $path = dir_path($path);
    $temp = explode('/', $path);
    $cur_dir = '';
    $max = count($temp) - 1;
    for ($i = 0; $i < $max; $i++) {
        $cur_dir .= $temp[$i] . '/';
        if (@is_dir($cur_dir))
            continue;
        @mkdir($cur_dir, 0777, true);
        @chmod($cur_dir, 0777);
    }

    return is_dir($path);
}

function dir_path($path): array|string
{
    $path = str_replace('\\', '/', $path);
    if (!str_ends_with($path, '/'))
        $path = $path . '/';

    return $path;
}

function sp_random_string($len = 8): string
{
    $chars = array(
        "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
        "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
        "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
        "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
        "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
        "3", "4", "5", "6", "7", "8", "9"
    );
    $charsLen = count($chars) - 1;
    shuffle($chars); // 将数组打乱
    $output = "";
    for ($i = 0; $i < $len; $i++) {
        $output .= $chars[mt_rand(0, $charsLen)];
    }

    return $output;
}

/**
 * 递归删除文件夹
 * @param $dir
 * @param string $file_type
 */
function delFile($dir, string $file_type = ''): void
{
    if (is_dir($dir)) {
        $files = scandir($dir);
        // 打开目录 // 列出目录中的所有文件并去掉 . 和 ..
        foreach ($files as $filename) {
            if ($filename != '.' && $filename != '..') {
                if (!is_dir($dir . '/' . $filename)) {
                    if (empty($file_type)) {
                        unlink($dir . '/' . $filename);
                    } else {
                        if (is_array($file_type)) {
                            // 正则匹配指定文件
                            if (preg_match($file_type[0], $filename)) {
                                unlink($dir . '/' . $filename);
                            }
                        } else {
                            // 指定包含某些字符串的文件
                            if (stristr($filename, $file_type)) {
                                unlink($dir . '/' . $filename);
                            }
                        }
                    }
                } else {
                    delFile($dir . '/' . $filename);
                    rmdir($dir . '/' . $filename);
                }
            }
        }
    } else {
        if (file_exists($dir)) unlink($dir);
    }
}

/**
 * 错误提示方法
 * @param $str
 */
#[NoReturn] function showHtml($str): void
{
    echo '
		<html>
        <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        </head>
        <body>
        ' . $str . '
        </body>
        </html>';
    exit;
}

/**
 * 计算签名
 * @param string $path
 * @throws Exception
 */
function getFileSignature(string $path): void
{
    global $fileValue;
    if (!is_dir($path)) {
        $fileValue .= @md5_file($path);
    } else {
        if (!$dh = opendir($path)) throw new Exception($path . " File open failed!");
        while (($file = readdir($dh)) != false) {
            if ($file == "." || $file == "..") {
                continue;
            } else {
                getFileSignature($path . DIRECTORY_SEPARATOR . $file);
            }
        }
        closedir($dh);
    }
}

/**
 * 写入签名
 * @return void
 * @throws Exception
 */
function generateSignature(): void
{
    $file = APP_DIR . '.version';
    if (!$data = @file($file)) {
        throw new Exception('.version读取失败');
    }
    $list = [];
    if (!empty($data)) {
        foreach ($data as $datum) {
            list($name, $value) = explode('=', $datum);
            $list[$name] = rtrim($value);
        }
    }

    global $fileValue;
    getFileSignature(APP_DIR . DIRECTORY_SEPARATOR . 'app');
    getFileSignature(APP_DIR . DIRECTORY_SEPARATOR . 'kitego');

    $list['project_signature'] = md5($fileValue);

    $str = "";
    foreach ($list as $key => $item) {
        $str .= "{$key}={$item}\n";
    }

    file_put_contents($file, $str);
}
